<template>
  <div>
    <el-card class="box-card">
      <div slot="header"
           class="clearfix">
        <el-tabs class="tab-left"
                 v-model="activeName">
          <el-tab-pane label="阅读量"
                       name="sale">
            <div>
              <el-row :gutter="10">
                <el-col :span="16">
                  <div class="charts"
                       height="400"
                       ref="charts"></div>
                </el-col>
                <el-col :span="8">
                  <ul class="list-rank">
                    <h1>文章浏览量排行</h1>
                    <dv-scroll-board :config="config"
                                     style="width:100%;height:80%" />
                  </ul>

                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="传感数据"
                       v-if="sensorFlag"
                       name="visit">
            <div>
              <el-row :gutter="10">
                <el-col :span="16"
                        style="text-align:center">
                  <h1>传感器最新数据</h1>
                  <div class="charts"
                       style="width:400px;height:400px"
                       ref="pannel"></div>
                </el-col>
                <el-col :span="8">
                  <div>
                    <h1>传感器历史数据</h1>
                    <el-table :data="sensorData"
                              style="width: 100%"
                              max-height="400">
                      <el-table-column fixed
                                       prop="datetime"
                                       label="时间"
                                       width="150">
                      </el-table-column>
                      <el-table-column prop="sensor"
                                       label="传感器"
                                       width="120">
                      </el-table-column>
                      <el-table-column prop="distantData"
                                       label="数据">
                      </el-table-column>

                    </el-table>
                  </div>

                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- <div class="tab-right">
          <span @click="setDay">今日</span>
          <span @click="setWeek">本周</span>
          <span @click="setMonth">本月</span>
          <span @click="setYear">本年</span>
          <el-date-picker type="daterange"
                          style="margin: 0 10px; width: 250px"
                          size="mini"
                          v-model="date"
                          format="yyyy年MM月dd日"
                          range-separator="-"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
        </div> -->
      </div>

    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs"
export default {
  props: {},
  components: {},
  data () {
    return {
      // 日期
      date: "",
      //   选中的tab
      activeName: "sale",
      wxid: "",
      charts: null,
      config: {
        data: [
        ],
        header: ['文章', '浏览量', '点赞数'],
        index: true,
        pannel: null,
        align: ['center']
      },
      sensorData: [],
      pannelOption: {},
      sensorFlag: true
    };
  },
  created () { },
  mounted () {
    this.getChartViewed()
    this.setViewedChart()
    this.setPannelChart()
    var that = this
    this.$bus.$on("sensorStatus", status => {
      console.log('传感器状态', status);
      that.sensorFlag = status
    })
    this.getLatestSensorData()
  },
  computed: {
    //   根据tab按钮切换标题
    title () {
      return this.activeName == "sale" ? "阅读量" : "访问量"
    }
  },
  watch: {
    //   监听title属性改变后更改柱状图标题
    title () {
      this.charts.setOption({
        title: {
          text: this.title
        }
      })
    }
  },
  methods: {
    //   本日
    setDay () {
      let day = dayjs().format("YYYY-MM-DD")
      this.date = [day, day]
    },
    // 本周
    setWeek () {
      let day1 = dayjs().date(0).format("YYYY-MM-DD")
      let day2 = dayjs().date(6).format("YYYY-MM-DD")
      this.date = [day1, day2]
    },
    // 本月
    setMonth () {
      let day1 = dayjs().startOf("month").format("YYYY-MM-DD")
      let day2 = dayjs().endOf("month").format("YYYY-MM-DD")
      this.date = [day1, day2]
    },
    // 本年
    setYear () {
      let day1 = dayjs().startOf("year").format("YYYY-MM-DD")
      let day2 = dayjs().endOf("year").format("YYYY-MM-DD")
      this.date = [day1, day2]
    },
    async getChartViewed () {
      const { data: res } = await this.$API.chart.articleRank()
      console.log(res);
      var that = this
      res.forEach(item => {
        let alist = []
        alist.push(item.title)
        alist.push(String(item.viewed))
        alist.push(String(item.thumb))
        that.config.data.push(alist)
      })
      this.config = { ...this.config }
    },
    setViewedChart () {
      this.charts = echarts.init(this.$refs.charts);
      this.charts.setOption({
        title: {
          text: "阅读量"
        },
        visualMap: [
          {
            show: false,
            type: 'continuous',
            seriesIndex: 0,
            min: 0,
            max: 400
          },
          {
            show: false,
            type: 'continuous',
            seriesIndex: 1,
            dimension: 0,
            min: 0,
            max: 12
          }
        ],
        xAxis: {
          type: "category",
          data: [
            "一月",
            "二月",
            "三月",
            "四月",
            "五月",
            "六月",
            "七月",
            "八月",
            "九月",
            "十月",
            "十一月",
            "十二月",
          ],
        },
        tooltip: {
          trigger: 'axis'
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130, 120, 200, 150, 80, 70],
            type: "line",
            showBackground: true,
            showSymbol: false,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
          },
        ],
      });
    },
    // 获取最新数据
    getLatestSensorData () {
      setInterval(() => {
        var that = this
        that.$bus.$on("sensorId", async (id) => {
          console.log('sensorId', id);

          that.wxid = id
          if (that.wxid) {
            const res = await this.$API.chart.getDistantData(that.wxid, 'latest')
            console.log('sensorData', res);
            this.pannelOption.series[0].data[0].value = res.data.distantData
            this.pannel.setOption(this.pannelOption, true)
            const res2 = await this.$API.chart.getDistantData(that.wxid, 'history')
            console.log("historyres", res2);
            let datas = []
            res2.data.forEach(item => {
              datas.push({ datetime: item.create_time, distantData: item.distantData, sensor: '超声波' });
            })
            that.sensorData = datas

          }
        })
      }, 1000)
    },
    // 设置echarts
    setPannelChart () {
      this.pannel = echarts.init(this.$refs.pannel)
      this.pannelOption = {
        series: [
          {
            type: 'gauge',
            axisLine: {
              lineStyle: {
                width: 30,
                color: [
                  [0.3, '#fd666d'],
                  [0.7, '#37a2da'],
                  [1, '#67e0e3']
                ]
              }
            },
            pointer: {
              itemStyle: {
                color: 'auto'
              }
            },
            axisTick: {
              distance: -30,
              length: 8,
              lineStyle: {
                color: '#fff',
                width: 2
              }
            },
            splitLine: {
              distance: -30,
              length: 30,
              lineStyle: {
                color: '#fff',
                width: 4
              }
            },
            axisLabel: {
              color: 'auto',
              distance: 40,
              fontSize: 20
            },
            detail: {
              valueAnimation: true,
              formatter: '{value} cm',
              color: 'auto'
            },
            data: [
              {
                value: 70
              }
            ]
          }
        ]
      }
      this.pannel.setOption(this.pannelOption, true)
    }
  },
};
</script>

<style scoped>
* {
  padding: 0px;
  margin: 0 auto;
}

.clearfix {
  position: relative;
  display: flex;
  justify-content: space-between;
}
.tab-left {
  width: 100%;
}
.tab-right {
  position: absolute;
  right: 0;
}
.tab-right span {
  margin: 0 10px;
}
.charts {
  width: 100%;
  height: 400px;
}
.list-rank {
  width: 100%;
  height: 400px;

  list-style: none;
}
.list-rank li {
  width: 100%;
  height: 10%;
  position: relative;
}
.list-icon {
  width: 20px;
  display: inline-block;
  text-align: center;
  height: 20px;
  line-height: 20px;
  background-color: black;
  position: absolute;
  color: white;
  border-radius: 50%;
}
.lvalue {
  position: absolute;
  left: 40px;
}
.rvalue {
  position: absolute;
  right: 0;
}
</style>
